
import BaseLabel_blxf from "./Common/BaseLabel";
import ShopRankPanel_blxf from "./Panel/shopRankPanel";

class UserGameData {
    /** 用户的微信头像 url */
    avatarUrl   : string = '';
    /** 用户的微信昵称 */
    nickname    : string = '';
    /** 用户的 openid */
    openid      : string = '';

    /** 用户的托管 KV数据列表 */
    KVDataList  : any[] = []
}

let wx = window['wx'];

const {ccclass, property} = cc._decorator;

/** 子域场景 */

@ccclass
export default class OpenData extends cc.Component {

    @property(cc.Node)
    UI = null;

    @property(cc.Prefab)
    shopRankPanel :cc.Prefab= null;

    @property({ type: cc.Node, tooltip: '财富排行' })
    userRankText: cc.Node = null;

    nextBundle: string = 'Friendly';


    @property({ tooltip: '好友排行榜数据' })
    friendRankList: UserGameData[] = [];

    @property({ tooltip: '用户信息' })
    userInfo: any = {};

    @property({ tooltip: '用户排行' })
    _userRankNum: number = 0;


    onLoad () {
        console.error('子域 onEanble');
        wx.onMessage( msg => {
            console.log('openData msg: ', msg);
            this.userInfo = msg.userInfo;
            switch( msg.event ){
                case 'setShopNum' : this.setShopNum( msg.value ); break;
                case 'getRank' : this.getRank(msg.options); break;
                case 'userRank' : this.onShowUserRank_blxf(); break;
                default : this.onOff(); break;
            }
        });
    }

    start () { 
        console.error('OpenData Scene');
        // cc.assetManager.loadBundle(this.nextBundle, (err)=>{
        // });
    }

    onOff(){
        this.userRankText.active = false;

        this.UI.destroyAllChildren();
    }

    public loadPrefab( options ){
        this.onOff();
        let node =   cc.instantiate(this.shopRankPanel)
        this.UI.addChild(node);
        node.position = cc.v3();
        node.getComponent(ShopRankPanel_blxf).initData_blxf( options );
    }

    // 显示玩家财富排行
    onShowUserRank_blxf () {
        this.userRankText.active = true;

        let _rankText: string = `${this._userRankNum || '暂无排名'}`;
        let _userRankText: string = `财富排行: ${_rankText}`;
        this.userRankText.getComponent(BaseLabel_blxf).setText_blxf(`${_userRankText}`);
    }

    /**
     * 获取玩家分数
     */
    private getShopNum(): Promise<number> {
        return new Promise(resolve => {
            console.log('[getShopNum]');
            wx.getUserCloudStorage({
                keyList: ['shopNum'],
                success: (res: UserGameData) => {
                    console.log('[getShopNum]', 'success', res);
                    resolve(res.KVDataList[0] ? parseInt(res.KVDataList[0].value) : 0);
                },
                fail: ( e ) => {
                    console.log('[getShopNum]', 'fail', e);
                    resolve(-1);
                }
            });
        });
    }

    /**
     * 设置玩家商品数
     * @param value 商品数
     */
    private async setShopNum(value: number) {
        console.log('[setShopNum]', value);
        // let oldScore = await this.getShopNum();
        // if (oldScore === -1) return;
        // if (value > oldScore) {
            wx.setUserCloudStorage({
                KVDataList: [{
                    key: 'shopNum',
                    value: value.toString()
                }],
                success: () => {
                    console.log('[setShopNum]', 'success');
                },
                fail: ( e ) => {
                    console.log('[setShopNum]', 'fail', e);
                }
            });

            this.friendRankList.length > 0 && this.getRank( { isUpdateRank: true } );
        // }
    }

    /**
     * 获取排行榜
     */
    private async getRank ( options: any = {} ) {
        console.log('[getRank]');
        let { isUpdateRank } = options || {};
        // 显示加载动画
        this.showLoading();
        // 调用微信的函数
        await new Promise(resolve => {
            wx.getFriendCloudStorage({
                keyList: ['shopNum'],
                success: (res: any) => {
                    console.log('[getRank]', 'success', res);

                    this.friendRankList = res.data;

                    // 对数据进行排序
                    this.onSortRankList_blxf();

                    // 排序之后进行展示
                    !isUpdateRank && this.updateRankList( );
                    resolve( true );
                },
                fail: (res: any) => {
                    console.log('[getRank]', 'fail');
                    !isUpdateRank && this.updateRankList( );
                    resolve( true );
                },
            });
        });
        // 关闭加载动画
        this.hideLoading();
    }

    /** 对数据进行排序 */
    private onSortRankList_blxf () {
        this.friendRankList.sort((a: UserGameData, b: UserGameData) => {
            if (a.KVDataList.length === 0 && b.KVDataList.length === 0) return 0;
            if (a.KVDataList.length === 0) return 1;
            if (b.KVDataList.length === 0) return -1;
            return parseInt(b.KVDataList[0].value) - parseInt(a.KVDataList[0].value);
        });

        this.friendRankList.forEach( (item, index) =>{
            // 玩家数据
            let { nickName, avatarUrl } = this.userInfo || {};
            if ( !nickName ) return;

            avatarUrl = avatarUrl.split('qlogo')[1];
            if ( item.nickname != nickName ) return;
            if ( !item.avatarUrl.includes(avatarUrl) ) return;

            this._userRankNum = index + 1;
            item
        })
    }

    /**
     * 更新好友排行
     * @param data 数据
     */
    private updateRankList( ) {
        this.loadPrefab( { data: this.friendRankList, userInfo: this.userInfo });
        // let count = Math.max(data.length, this.content.childrenCount);
        // for (let i = 0; i < count; i++) {
        //     if (data[i] && this.content.children[i]) {
        //         // 已存在节点，更新并展示
        //         this.content.children[i].active = true;
        //         this.content.children[i].getComponent(RankItem).set(i + 1, data[i]);
        //     } else if (data[i] && !this.content.children[i]) {
        //         // 节点不足，再实例化一个，更新信息
        //         let node = cc.instantiate(this.itemPrefab);
        //         node.setParent(this.content);
        //         node.getComponent(RankItem).set(i + 1, data[i]);
        //     } else {
        //         // 节点多了，关掉吧
        //         this.content.children[i].active = false;
        //     }
        // }
    }

    /**
     * 显示加载动画
     */
    private showLoading() {
        // this.loading.active = true;
    }

    /**
     * 关闭加载动画
     */
    private hideLoading() {
        // this.loading.active = false;
    }
}
